package com.itheima.stock.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.itheima.stock.constant.StockConstant;
import com.itheima.stock.mapper.SysUserMapper;
import com.itheima.stock.pojo.entity.SysUser;
import com.itheima.stock.service.UserService;
import com.itheima.stock.utils.IdWorker;
import com.itheima.stock.vo.req.LoginReqVo;
import com.itheima.stock.vo.resp.LoginRespVo;
import com.itheima.stock.vo.resp.R;
import com.itheima.stock.vo.resp.ResponseCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service("userService")
@Slf4j
public class UserServiceImpl implements UserService {
//1.查人根据人名
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public SysUser findByUsername(String username) {
        return sysUserMapper.findUserInfoByUsername(username);
    }

    //2.登陆功能
    @Override
    public R<LoginRespVo> login(LoginReqVo vo) {
    if(vo==null || StringUtils.isBlank(vo.getUsername())||StringUtils.isBlank(vo.getPassword())){
        return R.error(ResponseCode.DATA_ERROR);//sessionid找不到
    }
    if(StringUtils.isBlank(vo.getCode())||StringUtils.isBlank(vo.getSessionId())){
        return R.error(ResponseCode.CHECK_CODE_ERROR);//过期
    }

    //查询验证码是否过期
        String redisCode = (String) redisTemplate.opsForValue().get("CK:" + vo.getSessionId());//获取验证码
    if(StringUtils.isBlank(redisCode)){
        return R.error(ResponseCode.CHECK_CODE_TIMEOUT);
    }
    //验证码是否空
    //判断验证码是否正确
        if(redisCode==null || !redisCode.equalsIgnoreCase(vo.getCode())){
            return R.error(ResponseCode.CHECK_CODE_ERROR.getMessage());
        }

        //根据username查询密文
        SysUser dbUser = sysUserMapper.findUserInfoByUsername(vo.getUsername());
        if (dbUser==null){
        R.error(ResponseCode.ACCOUNT_NOT_EXISTS);//用户名不存在
        }

        if(!passwordEncoder.matches(vo.getPassword(), dbUser.getPassword())){
            return R.error(ResponseCode.USERNAME_OR_PASSWORD_ERROR);//用户名或密码错误
        }
        //执行到这代表name-pwd-code正确均能查到，可以登陆
        LoginRespVo respVo = new LoginRespVo();
        BeanUtils.copyProperties(dbUser,respVo);
        return R.ok(respVo);
    }

    //验证码
    @Override
    public R<Map> getCaptchaCode() {
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(250, 40, 4, 5);
        captcha.setBackground(Color.LIGHT_GRAY);
        String checkCode = captcha.getCode();//数字验证码
        String imageData = captcha.getImageBase64();//图片验证码
        String sessionId = String.valueOf(idWorker.nextId());//雪花算法sessionid
        log.info("当前生成图片校验码:{},会话id:{}",checkCode,sessionId);

        //保存到redis
        redisTemplate.opsForValue().set(StockConstant.CHECK_PREFIX +sessionId,checkCode,5, TimeUnit.MINUTES);

        //封装到map给前端
        HashMap<String, String> data = new HashMap<>();
        data.put("imageData", imageData);
        data.put("sessionId", sessionId);

        return R.ok(data);
    }
}
